const jwt = require('jsonwebtoken');

// token 校验中间件
function verifyToken(req, res, next) {
  const authHeader = req.headers.authorization;

  if (!authHeader) {
    return res.status(401).send({
      code: 401,
      message: '未登录，缺少 token',
    });
  }

  const token = authHeader.replace('Bearer ', ''); 

  jwt.verify(token, 'abc', (err, decoded) => {
    if (err) {
      return res.status(401).send({
        code: 401,
        message: 'token 已失效或无效，请重新登录',
      });
    }

    req.tokenData = decoded;
    next(); 
  });
}

module.exports = verifyToken;
